
export default class Socket{
    // 实例化
   wsUrl:string;
   constructor (wsUrl:string){
       this.wsUrl = wsUrl;
   }
   ModeCode={
    MSG:"message", //普通消息
    HEART_BEAT:"heart_beat", //心跳检查消息
   }
   ws=null as any; //websocket实例
   WebSocketState= false ; //是否连接
   hearBeat={
    time:4*1000, //心跳间隔
    timeout:  3*1000, //心跳超时时间
    reconnect:10*1000, //重连时间
   }
   reconnectTimer=null as any; //重连定时器
   connectWebSocket(){
       this.ws= new WebSocket(this.wsUrl);
       this.init(); //初始化
   }
   init(){
        this.ws.addEventListener('open',()=>{
            this.WebSocketState = true; //连接成功
            this.hearBeat && this.hearBeat.time? this.startHeartBeat(this.hearBeat.time):""; //开启心跳
            console.log('开启');
        })
        this.ws.addEventListener("message",(e:any)=>{
            const data = JSON.parse(e.data);
            switch(data.ModeCode){
                case this.ModeCode.MSG:
                    console.log("收到普通消息");
                    break;
                case this.ModeCode.HEART_BEAT:
                    this.WebSocketState=true
                    console.log("收到心跳消息",data.msg);
                    break;
            }  
        })

        this.ws.addEventListener("close",(e:any)=>{
            this.WebSocketState=false;
            console.log("断开了连接",e);
        })

        this.ws.addEventListener("error",(e:any)=>{
            this.WebSocketState=false;
            this.reconnectWebSocket();
            console.log("连接发生错误",e);
        })
   }
   //心跳检测初始化函数
   startHeartBeat(time:any){
        setTimeout(()=>{
            this.ws.send(
                JSON.stringify({
                    ModeCode:this.ModeCode.HEART_BEAT,
                    msg:new Date()
                })
            )
            this.waitingServer();
        },time)
   }
   //延时等待服务器端响应 通过WebSocketState判断是否连线成功
   waitingServer(){
       this.WebSocketState=false;
       setTimeout(()=>{
            if(this.WebSocketState){    
                this.startHeartBeat(this.hearBeat.time)
                return;
            }
            console.log("心跳无响应,已经断线了");
            try{
                this.ws.close();
            }
            catch(e){
                console.log("连接已经关闭");
            }
            this.reconnectWebSocket();
       },this.hearBeat.timeout)
   }
   //断线重连
   reconnectWebSocket(){
       this.reconnectTimer=setTimeout(()=>{
           this.reconnectWs();
       },this.hearBeat.reconnect);
   }
   reconnectWs(){
      if(!this.ws){
        this.connectWebSocket(); //重新连接
      }
      if(this.ws&&this.reconnectTimer){
        clearTimeout(this.reconnectTimer);//清除定时器
        this.ws.reconnectTimer=null; //重置定时器
        this.reconnectWebSocket() //重新连接
      }
   }
}